package com.gzxw.mogublog.picture.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.commons.entity.File;
import com.gzxw.mogublog.picture.mapper.FileMapper;
import com.gzxw.mogublog.picture.service.FileService;
import com.gzxw.mogublog.picture.util.AliyunUtil;
import com.gzxw.mogublog.utils.FileUtils;
import com.gzxw.mogublog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Autowired
    private AliyunUtil aliyunUtil;

    @Override
    public String uploadPicture(MultipartFile multipartFile, HttpServletRequest request) {

        if (Objects.isNull(multipartFile)) {
            return "上传的文件不能为空";
        }
        String localUrl = aliyunUtil.uploadFile(multipartFile);
        // 扩展名
        String picExpandedName = FileUtils.getPicExpandedName(multipartFile.getOriginalFilename());

        // 添加到数据库
        File file = new File();
        file.setCreateTime(new Date(System.currentTimeMillis()));
        file.setFileSortUid("a9a747d944c24845815356f72723ef8e");
        file.setFileOldName(multipartFile.getName());
        file.setFileSize(multipartFile.getSize());
        file.setPicExpandedName(picExpandedName);
        file.setPicName(System.currentTimeMillis()+"."+picExpandedName);
        file.setPicUrl(localUrl);
        file.setStatus(1);
        file.insert();

        return JSON.toJSONString(file);
    }

    @Override
    public File getPicture(String fileId) {

        QueryWrapper<File> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.eq("status",1);
        fileQueryWrapper.eq("uid",fileId);
        File file = baseMapper.selectOne(fileQueryWrapper);
        return file;
    }

    @Override
    public List<File> getPictures(List<String> fileIds) {


        Collection<File> fileList = this.listByIds(fileIds);
        List<File> list = new ArrayList<>(fileList);
        return list;
    }
}
